import { createRouter, createWebHistory } from 'vue-router'

// 布局
const MainLayout = () => import('@/layout/MainLayout.vue')

// 路由配置
const routes = [
  {
    path: '/',
    redirect: '/enterprise/traceability'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/enterprise',
    component: MainLayout,
    redirect: '/enterprise/traceability',
    children: [
      {
        path: 'traceability',
        name: 'TraceabilityManagement',
        component: () => import('@/views/enterprise/TraceabilityManagement.vue'),
        meta: { title: '溯源管理' }
      },
      {
        path: '/enterprise/traceability-detail/:id',
        name: 'traceabilityDetail',
        component: () => import('../views/enterprise/TraceabilityDetail.vue'),
        meta: { title: '溯源详情', requiresAuth: true },
        beforeEnter: (to, from, next) => {
          console.log('进入溯源详情路由, 参数:', to.params);
          next();
        }
      },
    ]
  },
  // 其他主要导航路由
  {
    path: '/company',
    component: MainLayout,
    redirect: '/company/index',
    children: [
      {
        path: 'index',
        name: 'CompanyIndex',
        component: () => import('@/views/company/CompanyIndex.vue'),
        meta: { title: '公司名称' }
      }
    ]
  },
  {
    path: '/group',
    component: MainLayout,
    redirect: '/group/index',
    children: [
      {
        path: 'index',
        name: 'GroupIndex',
        component: () => import('@/views/group/GroupIndex.vue'),
        meta: { title: '集团管理' }
      }
    ]
  },
  {
    path: '/platform',
    component: MainLayout,
    redirect: '/platform/index',
    children: [
      {
        path: 'index',
        name: 'PlatformIndex',
        component: () => import('@/views/platform/PlatformIndex.vue'),
        meta: { title: '平台运营' }
      }
    ]
  },
  {
    path: '/system',
    component: MainLayout,
    redirect: '/system/index',
    children: [
      {
        path: 'index',
        name: 'SystemIndex',
        component: () => import('@/views/system/SystemIndex.vue'),
        meta: { title: '系统设置' }
      }
    ]
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/NotFound.vue'),
    meta: { title: '404 - 页面不存在' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - ColdEatRabbit` : 'ColdEatRabbit'
  
  // 检查是否需要登录
  const token = localStorage.getItem('token')
  if (to.path !== '/login' && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router 